jQuery.noConflict();
(function($, PLUGIN_ID) {

    'use strict';

    var APPId = kintone.app.getId();
    var config = kintone.plugin.app.getConfig(PLUGIN_ID);
    if (!config) {return false;}
    var rowCount = Number(config['rowCount']);
    var relatedAppId = config['relatedAppId'];
    var balanceDate = config['balanceDate'];
    var subTable = config['subTable'];
    var currency = {};
    var exchangeRate = {};
    var i;
    var j;
    for (i = 0; i < rowCount; i++) {
        currency[i] = config['currency' + i];
        exchangeRate[i] = config['exchangeRate' + i];
    }

    var createChange = 'app.record.create.change.';
    var editChange = 'app.record.edit.change.';
    var indexEditChange = 'app.record.index.edit.change.';
    kintone.events.on(['app.record.edit.show', 'app.record.index.edit.show', 'app.record.create.show'],
        function(event) {
            var record = event.record;
            var thisExchangeRate;
            for (i = 0; i < rowCount; i++) {
                if (record[currency[i]]) {
                    thisExchangeRate = record[exchangeRate[i]];
                    thisExchangeRate['disabled'] = true;
                } else if (currency[i] in record[subTable]['value'][i]['value']) {
                    var subTableLength = record[subTable]['value']['length'];
                    for (j = 0; j < subTableLength; j++) {
                        thisExchangeRate = record[subTable]['value'][j]['value'][exchangeRate[i]];
                        thisExchangeRate['disabled'] = true;
                    }
                } else {
                    continue;
                }
            }

            function loopGet(offset) {

                var relatedTableRecords;
                var totalCount;
                var url = kintone.api.url('/k/v1/records', true);
                var body = {
                    app: relatedAppId,
                    totalCount: true,
                    query: ' limit 100 offset ' + offset
                };

                function exchangeRateDisabled(thisLine, exchangeRateSubtableCode) {
                    var APPUrl = kintone.api.url('/k/v1/app/form/fields', true);
                    var params = {
                        app: APPId
                    };
                    kintone.api(APPUrl, 'GET', params, function(resp) {
                        var prop = resp.properties;
                        var exchangeRateSubtableLabel = prop[subTable]['fields'][exchangeRateSubtableCode]['label'];
                        var tdCount = $('.edit-subtable-gaia th').length - 1;
                        for (j = 0; j < tdCount; j++) {
                            if ($('.edit-subtable-gaia th').eq(j).text() === exchangeRateSubtableLabel) {
                                thisLine.parent().parent().next().
                                    children('td:eq(' + j + ')').find('input').attr('disabled', true);
                            }
                        }
                    });
                }

                function postExchangeRate(relatedTableRecords, balanceDateVal, currencyVal, exchangeRateCell) {
                    for (var t = 0; t < relatedTableRecords.length; t++) {
                        var relatedTableStartDate = relatedTableRecords[t]['startDate']['value'];
                        var relatedTableEndDate = relatedTableRecords[t]['endDate']['value'];
                        var relatedTableCurrency = relatedTableRecords[t]['currency']['value'];
                        if (relatedTableStartDate <= balanceDateVal && relatedTableEndDate >= balanceDateVal
                         && relatedTableCurrency === currencyVal) {
                            exchangeRateCell['value'] = relatedTableRecords[t]['exchangeRate']['value'];
                            exchangeRateCell['disabled'] = true;
                            break;
                        } else {
                            continue;
                        }
                    }
                }

                function getExchangeRate(record) {
                    var balanceDateVal = record[balanceDate]['value'];
                    var currencyVal;
                    var exchangeRateCell;
                    for (i = 0; i < rowCount; i++) {
                        if (record[currency[i]]) {
                            currencyVal = record[currency[i]]['value'];
                            exchangeRateCell = record[exchangeRate[i]];
                            postExchangeRate(relatedTableRecords, balanceDateVal, currencyVal, exchangeRateCell);
                        } else if (currency[i] in record[subTable]['value'][i]['value']) {
                            for (j = 0; j < record[subTable]['value']['length']; j++) {
                                currencyVal = record[subTable]['value'][j]['value'][currency[i]]['value'];
                                exchangeRateCell = record[subTable]['value'][j]['value'][exchangeRate[i]];
                                postExchangeRate(relatedTableRecords, balanceDateVal, currencyVal, exchangeRateCell);
                            }
                        }
                    }
                }

                function exchangeRateTableGetValue(thiscurrency) {
                    kintone.events.on([createChange + balanceDate, createChange + thiscurrency,
                        editChange + balanceDate, editChange + thiscurrency, indexEditChange + balanceDate,
                        indexEditChange + thiscurrency], function(ev) {
                        record = ev.record;
                        getExchangeRate(record);
                        return ev;
                    });
                }

                kintone.api(url, 'GET', body, function(resp) {
                    // success:

                    relatedTableRecords = resp.records;
                    totalCount = resp.totalCount - 100;
                    if (offset <= totalCount) {
                        var data = offset + 100;
                        loopGet(data);
                    }

                    for (i = 0; i < rowCount; i++) {
                        exchangeRateTableGetValue(currency[i]);
                    }

                    $('.edit-subtable-gaia').on('click', '.add-row-image-gaia', function() {
                        for (i = 0; i < rowCount; i++) {
                            if (record[subTable]['value'][0]['value'][exchangeRate[i]]) {
                                exchangeRateSubtableCode = exchangeRate[i];
                                exchangeRateDisabled($(this), exchangeRateSubtableCode);
                            }
                        }
                    });
                });



            }

            loopGet(0);

            return event;
        });

})(jQuery, kintone.$PLUGIN_ID);
